package com.mercycrazy.recruit.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 分页对象定义
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2023-01-08
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PagedGridResult {

    /** 当前页数 */
    private int page;


    /** 总页数 */
    private long totalPages;

    /** 总记录数 */
    private long totalCounts;

    /** 每行显示的内容 */
    private List<?> rows;

    /**
     * 将 JPA Page 对象转换成 PagedGridResult
     */
    public static PagedGridResult of(Page<?> page) {

        PagedGridResult result = new PagedGridResult();

        result.setPage(page.getNumber() + 1);
        result.setTotalPages(page.getTotalPages());
        result.setTotalCounts(page.getTotalElements());
        result.setRows(page.getContent());

        return result;
    }

    /**
     * 将 JPA Page 对象转换成 PagedGridResult
     * content 需要做类型转换, 外界动态传入转换 Function
     */
    public static <S, T> PagedGridResult of(Page<S> page, Function<S, T> function) {

        PagedGridResult result = new PagedGridResult();

        result.setPage(page.getNumber() + 1);
        result.setTotalPages(page.getTotalPages());
        result.setTotalCounts(page.getTotalElements());

        List<S> originRows = page.getContent();

        List<T> targetRows = originRows.stream()
                .map(function)
                .collect(Collectors.toList());

        result.setRows(targetRows);

        return result;
    }
}